#include "stdafx.h"
#include "net/StreamSocketImpl.hpp"
#include "thread/thread.hpp"
using JHCPP::thread::CThread;

NET_NAMESPACE_BEGIN

CStreamSocketImpl::CStreamSocketImpl()
{
}

CStreamSocketImpl::CStreamSocketImpl(CIPAddress::Family family)
{
	if (family == CIPAddress::IPv4)
		init(AF_INET);
#if defined(JH_HAVE_IPv6)
	else if (family == CIPAddress::IPv6)
		init(AF_INET6);
#endif
	else 
		throw InvalidArgumentException("Invalid or unsupported address family passed to StreamSocketImpl");
}

CStreamSocketImpl::CStreamSocketImpl(JH_SOCKET sockfd) : CSocketImpl(sockfd)
{
}

CStreamSocketImpl::~CStreamSocketImpl()
{
}

int CStreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
{
	const char* p = reinterpret_cast<const char*>(buffer);
	int remaining = length;
	int sent = 0;
	bool blocking = getBlocking();
	while (remaining > 0)
	{
		int n = CSocketImpl::sendBytes(p, remaining, flags);
		jh_assert_dbg(n >= 0);
		p += n; 
		sent += n;
		remaining -= n;
		if (blocking && remaining > 0)
			CThread::yield();
		else
			break;
	}
	return sent;
}

NET_NAMESPACE_END
